package paper.web.controller.paper;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import keter.domain.validation.BeanValidators;
import keter.exception.KeterValidationException;
import keter.web.util.MediaTypes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import paper.dao.CommentsDao;
import paper.domain.Accessory;
import paper.domain.Comments;
import paper.domain.Paper;
import paper.domain.UploadItem;
import paper.domain.User;
import paper.service.PaperService;
import paper.util.ConfigConstant;
import paper.web.controller.BaseController;
import paper.web.util.WebUtil;

/**
 * <p>Class       : paper.web.controller.LoginController
 * <p>Descdription: 登录跳转逻辑控制器
 * @author  顾力行-gulixing@msn.com
 * @version 1.0.0
 */  
@Controller
@RequestMapping("/paper/paper")
public class PaperController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(PaperController.class);

    @Autowired
    PaperService service;
    
	@Autowired
	CommentsDao cdao;
    
	public static class Views {
		private static final String Prefix = "paper/paper";
		static final String Index = to_(Prefix) + "index";
		static final String View = to_(Prefix) + "view";
		static final String Add = to_(Prefix) + "add";
		static final String Update = to_(Prefix) + "update";
		static final String Delete = to_(Prefix) + "delete";
	}
	
	public PaperController() {
	}
	
	/**
	 * <p>Method ：getCurrentReport
	 * <p>Description : 学生获取当前唯一论文
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	private Paper getCurrentPaper(){
		List<Paper> list = service.getDao().findByCreator(getCurrentUser().getId());
		if(list!=null && !list.isEmpty()){
			return list.get(0);
		}
		return new Paper();
	}
	
	/**
	 * <p>Method ：login
	 * <p>Description : 处理控制台请求
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = Routes.Index, method = RequestMethod.GET)
	public String index(Model model) {
		model.addAttribute("paper", getCurrentPaper());
		List<Comments> list = cdao.findByMainId(getCurrentPaper().getId());
		model.addAttribute("comments", list);
		model.addAttribute("count", list.size());
		return Views.Index;
	}
	
	/**
	 * <p>Method ：view
	 * <p>Description : 教师功能-查看指定论文
	 * @param id
	 * @param model
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@PreAuthorize("hasRole('TEACHER')")
	@RequestMapping(value = Routes.View, method = RequestMethod.GET)
	public String view(@PathVariable Long id, Model model) {
		model.addAttribute("paper", service.getDao().findOne(id));
		return Views.Index;
	}
	
	/**
	 * <p>Method ：update
	 * <p>Description : 进入创建|修改页面
	 * @param model
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public String update(Model model) {
		model.addAttribute(new UploadItem());
		model.addAttribute("paper", getCurrentPaper());
		model.addAttribute("fileSize", ConfigConstant.getFileMaxSizeText());
		model.addAttribute("fileExt", ConfigConstant.paperFileExt);
		return Views.Update;
	}
	
	/**
	 * <p>Method ：update
	 * <p>Description : 更新论文
	 * @param uploadItem
	 * @param model
	 * @param request
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(UploadItem uploadItem, Model model, HttpServletRequest request) {
		MultipartHttpServletRequest req = (MultipartHttpServletRequest)request;
		// 1. 新建或更新报告
		Paper p = getCurrentPaper();
		p.setCreator(getCurrentUser());
		p.setName(req.getParameter("name"));
		p.setContent(request.getParameter("content"));
		BeanValidators.validateWithException(validator, p);
		service.getDao().save(p);
		String redirectUrl = "/paper/paper/update";
		// 2. 上传数据
        try {
            MultipartFile file = uploadItem.getFileData();
            if (file.getSize() > 0) {
            	try {
					WebUtil.validateUploadFile(file,ConfigConstant.paperFileExt,ConfigConstant.fileMaxSize);
				} catch (KeterValidationException kve) {
					model.addAttribute("updateMessage", kve.getMessage());
                    return redirectToUrl(redirectUrl);
				}
                InputStream inputStream = file.getInputStream();
                //写入磁盘文件
                Accessory acc = service.writeFile((User)getCurrentUser(),file.getOriginalFilename(), inputStream);
                //删除原附件
                if(p.getAccessoryId()!=null){
                	try {
						service.getAccessoryDao().delete(p.getAccessoryId());
					} catch (Exception e) {
						//防止因删除失败导致附件无法上传成功
						logger.error("删除附件表id为["+p.getAccessoryId()+"]的数据时出现异常",e);
					}
                }
                //更新report的附件id
                p.setAccessoryId(acc.getId());
                p.setAccessoryFileId(acc.getFileId());
                service.getDao().save(p);
            }
            model.addAttribute("updateMessage", "保存成功！");
        } catch (Exception e) {
            model.addAttribute("updateMessage", "文件上传失败！");
        	logger.error("文件上传失败，异常信息:",e);
        }		
        return redirectToUrl(redirectUrl);
    }
	
	 
	@RequestMapping(value = Routes.Downlaod, method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) throws Exception {
		Accessory acc = service.getAccessoryDao().findByFileId(id);
		String ctxPath = ConfigConstant.fileStoreRootPath;
		String downLoadPath = ctxPath + acc.getFilePath() + ConfigConstant.PAPER_FILE_NAME;		
		WebUtil.makeDownload(request, response, downLoadPath, acc.getName());
	}
	
	/**
	 * <p>Method ：submit
	 * <p>Description : 提交论文
	 * @return 
	 * @author  gulixing@msn.com
	 * @version 1.0.0
	 */
	@RequestMapping(value = "/submit", method = RequestMethod.POST, consumes = MediaTypes.JSON)
	@ResponseBody
	public Map<String, String> submit() {
		Map<String, String> ajaxMap = getAjaxMap();
		Paper paper = getCurrentPaper();
		paper.setMaster(getCurrentUser().getTeacher());
		service.submit(paper);
		return ajaxMap;
	}
	
	
	@RequestMapping(value = "/viewcomments/{paperId}", method = RequestMethod.GET)
	@ResponseBody
	public List<Comments> comments(@PathVariable Long paperId){
    	return cdao.findByMainId(paperId);
	}
}